package com.yishusmt.wechatapi.wechatdev.config;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhangyi
 * @date 2018/8/11 9:59
 */
@Configuration
public class HttpConfig {

    @Value("${http.maxTotal}")
    private Integer maxTotal;

    @Value("${http.defaultMaxPerRoute}")
    private Integer defaultMaxPerRoute;

    @Value("${http.connectionOut}")
    private Integer connectionOut;

    @Value("${http.connectionRequestTimeOut}")
    private Integer connectionRequestTimeOut;

    @Value("${http.socketTimeOut}")
    private Integer socketTimeOut;

    @Value("${http.staleConnectionCheckEnable}")
    private Boolean staleConnectCheckEnable;

    /**
     * 实例化一个连接池管理器，设置配置参数
     *
     * @return
     */
    @Bean("httpClientConnectionManager")
    public PoolingHttpClientConnectionManager getPoolingHttpClientConnectionManage(){
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        manager.setMaxTotal(maxTotal);
        manager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        return manager;
    }

    /**
     * 实例化连接池，设置连接池管理器
     *
     * @param poolingHttpClientConnectionManager
     * @return
     */
    @Bean("httpClientBuilder")
    public HttpClientBuilder getHttpClientBuilder(@Autowired PoolingHttpClientConnectionManager poolingHttpClientConnectionManager){

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
        return  httpClientBuilder;
    }

    /**
     * 获取httpClient
     *
     * @param httpClientBuilder
     * @return
     */
    @Bean
    public CloseableHttpClient getCloseableHttpClient(@Autowired HttpClientBuilder httpClientBuilder){
        return httpClientBuilder.build();
    }

    @Bean("builder")
    public RequestConfig.Builder getBuiler(){
        RequestConfig.Builder builder = RequestConfig.custom();
        return builder.setConnectionRequestTimeout(connectionRequestTimeOut)
                .setConnectTimeout(connectionOut)
                .setSocketTimeout(socketTimeOut)
                .setStaleConnectionCheckEnabled(staleConnectCheckEnable);
    }

    /**
     *
     *
     * @param builder
     * @return
     */
    @Bean
    public RequestConfig getRequestConfig(@Autowired RequestConfig.Builder builder){
        return builder.build();
    }
}
